package cn.edu.tju.cas.util;

import cn.edu.tju.cas.entity.UserEntity;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created by catold on 16/4/9.
 */
public class SessionUtil {
    /**
     * 获取session
     *
     * @return
     */
    public static HttpSession getSession() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }

    public static String getTicket() {
        return (String)getSession().getAttribute("ticket");
    }

    public static void setTicket(String ticket) {
        getSession().setAttribute("ticket", ticket);
    }

    /**
     * 获取登录用户
     *
     * @return
     */
    public static UserEntity getUser() {
        return (UserEntity) getSession().getAttribute("user");
    }

    /**
     * 设置user
     * @param user
     */
    public static void setUser(UserEntity user) {
        getSession().setAttribute("user", user);
    }

    /**
     * 设置是否登录
     * @param isLogin
     */
    public static void setLogin(boolean isLogin) {
        getSession().setAttribute("isLogin", isLogin);
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    public static boolean isLogin() {
        HttpSession session = getSession();

        Object islogin = session.getAttribute("isLogin");
        if (islogin == null) {
            session.setAttribute("isLogin", false);
            islogin = false;
        }
        return (boolean) islogin;
    }

    /**
     * 返回是否是管理员
     *
     * @return
     */
    public static boolean isAdmin() {
        return getUser().getIsAdmin() == 1;
    }

    /**
     * 是不是超级管理员
     * @return
     */
    public static boolean isSuperAdmin(){
        return getUser().getUsername().equals("admin");
    }

    /**
     * 清理sesson
     */
    public static void clear(){
        getSession().invalidate();
    }
}
